<template>
    <div class="container mt-2">

        <h3>
            {{ info?.title }}
        </h3>
        <p>
            <span class="badge badge-success" v-if="info.status">已解决</span>
            <span class="badge badge-secondary" v-else>未解决</span>
        </p>
        <p>浏览量: {{ info.visit }}</p>
        <p>发布时间: {{ new Date(info.create_time).toLocaleString() }}</p>
        <p>发布作者: {{ info.user?.username }}</p>
        <hr>
        <div class="rich-text" v-html="info?.content"></div>
        <el-card shadow="hover">
            <el-form @submit.prevent="submit" label-position="top">
                <el-form-item>
                    <div>
                        <Toolbar style="border-bottom: 1px solid #ddd" :editor="editorRef"
                            :defaultConfig="toolbarConfig" :mode="mode" />
                        <Editor style="height: 200px; overflow-y: hidden;" v-model="formData.answer"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                    </div>
                </el-form-item>
            </el-form>
            <template #header>
                <div class="action-right">
                    <el-button @click="submit" type="primary">立即回答</el-button>
                </div>
            </template>
        </el-card>
        <el-divider content-position="left">
            <h5>全部回答</h5>
        </el-divider>
        <div class="media shadow-sm p-2 mb-2" v-for="item in answerList" :key="item.id">
            <el-avatar :size="80" src="http://picsum.photos/80" />
            <div class="media-body ml-4">
                <h6 class="mt-0">{{ item.user.username }}</h6>
                <p v-html="item.answer.slice(0, 120)"></p>
                <p>{{ new Date(item.create_time).toLocaleString() }}</p>
                <el-row>
                    <el-col :span="3" :offset="21">
                        <el-button @click="$router.push({ name: 'answer', params: { id: item.uuid } })" plain
                            type="primary" round>查看详情</el-button>
                    </el-col>
                </el-row>
            </div>
        </div>
        <el-empty v-if="answerList.length === 0" description="暂无数据"></el-empty>
    </div>
</template>
<script setup>
import http from '@/utils/http';
import { onBeforeUnmount, shallowRef, ref, onMounted, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
const serverHost = inject('host')
let editorRef = shallowRef()
const mode = 'simple'
const toolbarConfig = {}
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            fieldName: 'image',
            server: `${serverHost}/api/upload/wang_editor_upload/`
        }
    }
}

const route = useRoute()
const router = useRouter()
const formData = ref({
    answer: ''
})
const info = ref({})
const answerList = ref([])
const answerCount = ref([])
const getAnswerList = async (que_id) => {
    const { status, data } = await http.get(`/api/questions/${que_id}/answers/`)
    if (status === 200) {
        answerList.value = data.results
        answerCount.value = data.count
    }
}
onMounted(async () => {
    const { params } = route
    // 获取提问详情数据
    try {
        const { status, data } = await http.get(`/api/questions/${params.id}/`)
        if (status === 200) {
            info.value = data
            // 请求解答列表
            await getAnswerList(data.id)
        }
    } catch{ 
        router.replace({ path: "/404" })
    }

})
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
// 发布解答
const submit = async () => {
    if (formData.value.answer == '<p><br></p>') {
        ElMessage.closeAll()
        return ElMessage.warning('请输入回答内容')
    }
    const { status } = await http.post('/api/answer/', { ...formData.value, que_id: info.value.id })
    if (status === 201) {
        ElMessage.success('发布成功')
        formData.value = { answer: "" }
        location.reload()
    }
}

</script>
